#include "AQ_File.h"

bool AQ_FileExist(const char* szFilePath) {
	if(!szFilePath)	return false;

	if(0 == access(szFilePath, F_OK))	return true;

	return false;
}

char* AQ_FileGetName(const char* szFilePath) {
	char* p = NULL;

	if(!szFilePath)	return NULL;

	p = strrchr(szFilePath, '/');

	return p? p+1 : (char*)szFilePath;
}

char* AQ_FileGetDir(const char* szFilePath) {
	return dirname(szFilePath);
}

char* AQ_FileGetExt(const char* szFilePath) {
	char* pFileName = AQ_FileGetName(szFilePath);
	char* pLastDot = strrchr(pFileName, '.');

	if(!pLastDot) return "";
	else {
		return pLastDot + 1;
	}
		
}

int AQ_FileGetSize(const char* szFilePath) {
	struct stat st;

	if(stat(szFilePath, &st) < 0)	return -1

	return st.st_size;
}



int AQ_FileLoad(const char* szFilePath,  void* pBuf, size_t nBufSize) {
	int iFd = -1;
	
	if(!szFilePath) return -1;
	if((iFd = open(szFilePath, O_RDONLY, 0)) < 0)		return -1;

	struct stat st;
	if(fstat(iFd, &st) < 0) {
		close(iFd);
		return -1;
	}

	nBufSize = st.st_size > nBufSize ? nBufSize : st.st_size;
	size_t nCount  =  read(iFd, pBuf, nBufSize);
	close(iFd);
	
	if(nBufSize != nCount) {
		return -1;
	}
	
	((char*)pBuf)[nCount] = '\0';
	
	return 0;
}

int AQ_FileSave(const char* szFilePath, const void* pBuf, size_t nBufSize, bool bAppend) {
	int iFd = -1;
	
	int iFlag = bAppend ? O_CREAT|O_WRONLY|O_APPEND : O_CREAT|O_WRONLY|O_TRUNC;
	
	iFd = open(szFilePath, iFlag, DEF_FILE_MODE);
	if(iFd < 0)	return -1;

	int iCount = write(iFd, pBuf, nBufSize);
	close(iFd);

	return iCount;
}

